/**
 * 链表节点类
 */
export class ListNode<T> {
  public value: T;
  public next: ListNode<T> | null;

  constructor(value: T) {
    this.value = value;
    this.next = null;
  }
}

/**
 * 链表类 - 实现单向链表数据结构
 */
export class LinkedList<T> {
  private head: ListNode<T> | null;
  private size: number;

  constructor() {
    this.head = null;
    this.size = 0;
  }

  /**
   * 获取链表长度
   */
  public get length(): number {
    return this.size;
  }

  /**
   * 检查链表是否为空
   */
  public isEmpty(): boolean {
    return this.size === 0;
  }

  /**
   * 在链表头部添加元素
   */
  public prepend(value: T): void {
    const newNode = new ListNode(value);
    newNode.next = this.head;
    this.head = newNode;
    this.size++;
  }

  /**
   * 在链表尾部添加元素
   */
  public append(value: T): void {
    const newNode = new ListNode(value);

    if (this.isEmpty()) {
      this.head = newNode;
    } else {
      let current = this.head;
      while (current?.next) {
        current = current.next;
      }
      if (current) {
        current.next = newNode;
      }
    }

    this.size++;
  }

  /**
   * 打印链表内容
   */
  public print(): void {
    let current = this.head;
    let result = '';

    while (current) {
      result += `${current.value} -> `;
      current = current.next;
    }

    result += 'null';
    console.warn(result);
  }

  /**
   * 遍历链表并返回数组表示（用于可视化）
   */
  public toArray(): T[] {
    const res: T[] = [];
    let current = this.head;
    while (current) {
      res.push(current.value);
      current = current.next;
    }
    return res;
  }
}
